
#ifndef _WEBKITCALLER_H_
#define _WEBKITCALLER_H_

#include <zmq.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <string>
#include <unistd.h>
#include <iconv.h>
#include <string>
#include <list>
#include <vector>
#include <boost/asio.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/archive/iterators/base64_from_binary.hpp>  
#include <boost/archive/iterators/binary_from_base64.hpp>  
#include <boost/archive/iterators/transform_width.hpp> 
#include <boost/thread/locks.hpp>
#include <boost/thread/mutex.hpp>
#include "WebKitPort.h"
#include "Zookit.h"
#include "json/json.h"

#define REQUEST_TIMEOUT 60000  // 1 min

namespace SpiderWebKitClient {

/* 
 * @classname GlobalConfig
 * @classdesc 一些全局的函数和设置
 */
class GlobalConfig {
    public:
    ~GlobalConfig();

    static GlobalConfig *instance();

    void connect(std::string zkhost);
    std::string getProtocolFromGroup(std::string group, bool isStatic);
    void* gZMQCTX();

    private:
    GlobalConfig();
    ZooKit *m_zk;
    void* m_gZMQCTX;
    static GlobalConfig *m_instance;
    boost::mutex m_mutex;
};

class WebKitCaller {
    public:
    WebKitCaller();
    ~WebKitCaller();

    void initDefault(std::string group, bool isStatic);
    void initWithServerProtocol(std::string protocol, bool isStatic);

    void getFreePid(bool isStatic);

    std::string getIPAddress();
    std::string webKitCall(long pageid, long funcid, std::list<std::string> &args, int timeout = REQUEST_TIMEOUT);

    bool Base64Encode(const std::string& input, std::string* output);
    bool Base64Decode(const std::string& input, std::vector<char> &output);
    bool Base64Decode(const std::string& input, std::string* output);

    std::string getReturnStringValue(std::string message);
    std::list<long> getReturnLongArrayValue(std::string message);
    long getReturnLongValue(std::string message);
    void getReturnRectValue(std::string message, int* x, int* y, int* w, int* h);
    bool getReturnBufferValue(std::string message, std::vector<char> &output);
    long getReturnPageValue(std::string message, long *page);
    std::string getReturnDownloadInfoValue(std::string message, std::map<std::string, std::string> &headers);
    std::list<Json::Value> getReturnJsonObjArrayValue(std::string message);
    bool checkAvailable();

    bool failed();

    private:
    std::string getCallJson(long pageid, long funcid, std::list<std::string> &args);

    std::string m_clientID;
    void *m_zmqClient;
    std::string m_wkServerIP;
    bool m_failed;
    bool m_connectFailed;
    int m_wkpid;
};

} // namespace SpiderWebKitClient
#endif

